﻿using System;
using System.Linq;
using System.Web;
using Artech.PetShop.Common;
using Artech.PetShop.Infrastructures.Interface;
using Artech.PetShop.Orders.BusinessEntity;
using Artech.PetShop.Orders.Service.Interface;
using Artech.PetShop.Products.Interface;

namespace Artech.PetShop.Orders
{
    public class OrderPresenter: PresenterBase<IOrderView>
    {
        private IOrderService _proxy = ServiceProxyFactory.Create<IOrderService>("orderservice");

        private Order Order
        {
            get
            {
                if (HttpContext.Current.Session["__Order"] == null)
                {
                    HttpContext.Current.Session["__Order"] = new Order();
                }

                return (Order)HttpContext.Current.Session["__Order"];
            }
        }

        public OrderPresenter(IOrderView view)
            : base(view)
        { }

        public void ShowOrderInfo()
        {
            string id = ServiceLoader.LoadService<IQueryStringResolverService>().GetValue("productid");
            if (!string.IsNullOrEmpty(id))
            {
                Guid productID = new Guid(id);
                Product product = ServiceLoader.LoadService<IProduct>().GetProduct(productID);
                if (product.Inventory < 1)
                {
                    throw new BusinessException("Lack of inventory.");
                }

                if (this.Order.Details.Count(item => item.ProductID == productID) == 0)
                {
                    this.Order.Details.Add(new OrderDetail { ProductID = productID, ProductName = product.ProductName, Quantity = 1, UnitPrice = product.UnitPrice });
                }
            }

            this.View.BindingOrderInfo(this.Order);
        }

        public void RemoveProductFromShippingCart(Guid productID)
        {
            OrderDetail detail = this.Order.Details.Where(item => item.ProductID == productID).ToArray<OrderDetail>()[0];
            this.Order.Details.Remove(detail);
            this.View.BindingOrderInfo(this.Order);
        }

        public void UpdateQuantity(Guid productID, int quantity)
        {
            Product product = ServiceLoader.LoadService<IProduct>().GetProduct(productID);
            if (product.Inventory < quantity)
            {
                throw new BusinessException("Lack of inventory.");
            }
            OrderDetail detail = this.Order.Details.Where(item => item.ProductID == productID).ToArray<OrderDetail>()[0];
            detail.Quantity = quantity;
            this.View.BindingOrderInfo(this.Order);
        }

        public void Submit()
        {
            this._proxy.Submit(this.Order);
            HttpContext.Current.Session["__Order"] = null;
            ServiceLoader.LoadService<INavigatorService>().Navigate("~/checkout.aspx");
        }
    }
}
